/*
 *所有关于Check_Report_Work类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Check_Report_WorkService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using System.Text.Json;
using static ATkg.BizAppProject.Controllers.Check_Report_WorkController;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json;

namespace ATkg.BizAppProject.Services
{
    public partial class Check_Report_WorkService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICheck_Report_WorkRepository _repository;//访问数据库
        private readonly AmesSyncService _amesSyncService;
        [ActivatorUtilitiesConstructor]
        public Check_Report_WorkService(
            ICheck_Report_WorkRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            AmesSyncService amesSyncService
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _amesSyncService = amesSyncService ?? throw new ArgumentNullException(nameof(amesSyncService));
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        // 将网页中填写的审核信息传入数据库
        public async Task<object> DealDataFromWeb(ActionModel model)
        {
            string Action = (string)model.Action;

            if (Action == "上机")
            {
                var action_content = new Check_Report_Work
                {

                    ProductId = (string)model.ProductCode,  // 产品代码
                    EquipmentNo = (string)model.EquipmentNo,  // 设备号
                    JianfenLot = (string)model.InspectionId,
                    DianduLot = (string)model.PlatingId,  
                    Qty = (int)model.Quantity,  
                    OperatorOnboard = (string)model.Username,  
                    TimeOnboard = (DateTime)model.CurrentTime,  
                };
                await Db.DoInsertAsync<Check_Report_Work>(action_content);
                //修改设备模块对应设备的状态
                //1.先用账号登录设备模块->获取uid (可以直接调用AmesSyncService)  (可以不用获取)
                //2.获取对应设备的id
                //3.调用接口修改设备状态
                //
                var uid = await _amesSyncService.GetOdooUid_Kg_Device("ccd@atmcn.com", "Ccd123456");
                var qDomain = new List<object>
                {
                    "&", // AND 条件
                    new List<object> { "nick_name", "=", action_content.EquipmentNo },
                    new List<object> { "department_id", "child_of", 9 },
                };


                var qFields = new List<string> {
                "id"
                };
                var qPage = new
                {
                    limit = 10000,
                    offset = 0,
                    context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                };
                var resp = await _amesSyncService.CallSearchRead_Kg_Device("maintenance.equipment", qDomain, qFields, qPage);
                var res = (JArray)resp["result"];
                var x = (JObject)res[0];
                var id = (int)x["id"]; //获取设备的id

                var param = new List<object>();
                param.Add(_amesSyncService.db_kg_device);
                param.Add(uid);
                param.Add(_amesSyncService.password_kg_device);
                param.Add("maintenance.equipment");
                param.Add("write");
                var vals = new Dictionary<string, object>
                {
                        { "ccd_status", "run" },  
                };
               
                param.Add(new List<object> { (int)id, vals });
                JObject data = null;
                try
                {
                    //整体内容的修改/添加
                    data = await _amesSyncService.Call_Kg_Device("object", "execute_kw", param);
                }
                catch (Exception ex)
                {
                    throw new AppException(ex.ToString());
                }


            }
            else if (Action == "下机") // 明确判断下机操作
            {
                var dianduLot = (string)model.PlatingId;

                // 1. 查询数据库中匹配DianduLot的上机记录
                // 使用EF Core标准方法查询：先获取DbSet，再筛选条件
                var existingRecord = await Db.Set<Check_Report_Work>()
                    .Where(x => x.DianduLot == dianduLot && x.OperatorOffload == null)
                    .FirstOrDefaultAsync();

                if (existingRecord == null)
                {
                    // 处理未找到对应上机记录的情况
                    throw new KeyNotFoundException($"未找到DianduLot为{dianduLot}的上机记录");
                }
                // 确保下机时间不为空
                var offloadTime = (DateTime)model.CurrentTime;
                if (offloadTime == default)
                {
                    throw new ArgumentException("下机时间不能为空");
                }
                // 检查上机时间是否存在（处理可空类型）
                if (!existingRecord.TimeOnboard.HasValue)
                {
                    throw new InvalidOperationException("上机记录未包含有效的上机时间，无法计算时长");
                }
                // 计算时长（先转换为非空DateTime再运算）
                TimeSpan timeSpan = offloadTime - existingRecord.TimeOnboard.Value;
                var duration = (decimal)Math.Round(timeSpan.TotalHours, 2);

                // 3. 更新下机信息
                existingRecord.OperatorOffload = (string)model.Username;
                existingRecord.TimeOffload = (DateTime)model.CurrentTime;
                existingRecord.Duration = (decimal)duration; // 保留两位小数

                // 4. 保存更新
                await Db.DoUpdateAsync<Check_Report_Work>(existingRecord);

                //修改设备模块对应设备的状态
                //1.先用账号登录设备模块->获取uid (可以直接调用AmesSyncService)  (可以不用获取)
                //2.获取对应设备的id
                //3.调用接口修改设备状态
                //
                var uid = await _amesSyncService.GetOdooUid_Kg_Device("ccd@atmcn.com", "Ccd123456");
                var qDomain = new List<object>
                {
                    "&", // AND 条件
                    new List<object> { "nick_name", "=", existingRecord.EquipmentNo },
                    new List<object> { "department_id", "child_of", 9 },
                };


                var qFields = new List<string> {
                "id"
                };
                var qPage = new
                {
                    limit = 10000,
                    offset = 0,
                    context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                };
                var resp = await _amesSyncService.CallSearchRead_Kg_Device("maintenance.equipment", qDomain, qFields, qPage);
                var res = (JArray)resp["result"];
                var x = (JObject)res[0];
                var id = (int)x["id"]; //获取设备的id

                var param = new List<object>();
                param.Add(_amesSyncService.db_kg_device);
                param.Add(uid);
                param.Add(_amesSyncService.password_kg_device);
                param.Add("maintenance.equipment");
                param.Add("write");
                var vals = new Dictionary<string, object>
                {
                        { "ccd_status", "waiting" },
                };

                param.Add(new List<object> { (int)id, vals });
                JObject data = null;
                try
                {
                    //整体内容的修改/添加
                    data = await _amesSyncService.Call_Kg_Device("object", "execute_kw", param);
                }
                catch (Exception ex)
                {
                    throw new AppException(ex.ToString());
                }
            }
            else
            {
                // 处理未知操作类型
                throw new ArgumentException($"不支持的操作类型：{Action}");
            }
            Console.WriteLine("操作记录已保存");
            return new { Success = true, Message = "操作记录已保存" };
        }
    }
}
